<script setup>

import XrCreateSingle from "@/szcomponent/XrCreateSingle/index.vue";
import CreateSections from "components/CreateSections.vue";
import {useErpUserStore} from "@/store/modules/usererp.js";
import WkFormItems from "components/NewCom/WkForm/WkFormItems.vue";
import {filedGetFieldAPI} from "@/api/crm/common.js";
import crmTypeModel from "@/views/crm/model/crmTypeModel.js";
import {useSzCustomFields} from "@/views/crm/hooks/create/useSzCustomFields.js";
import {crmCustomerSaveAPI} from "@/api/crm/customer.js";
import {ElMessage} from "element-plus";
import {useCreateCustomFieldHook} from "@/views/scrm/customer/create/useCreateCustomFieldHook.js";
import {useCreateGenerateRuleHook} from "@/views/scrm/customer/create/useCreateGenerateRuleHook.js";

const properties = defineProps({
  action: {
    type: Object,
    default: () => {
      // 默认是新建
      return {
        type: 'save',
        id: '',
        data: {}
      }
    }
  }
})

const optionData = reactive({
  //扁平化的基础的字段信息，从0开始排序
  baseFields: [],
  // 只有字段名称，其他信息去掉了
  fieldForm: {},
  // 按照表单设计的列信息，比如第一行两个，第二行三个
  fieldList: [],
  // 字段的规则信息
  fieldRules: {},

  imageData: {
    mainFile: [],
    detailFile: []
  }
})
const emits = defineEmits(['save-success', 'close'])

const title = computed(() => {
  return properties.action.type === 'update' ? '编辑客户' : '新建客户'
})

const crmFormRef = ref()

// 保存点击后的事件处理
function saveClick() {
  // const crmForm = .$refs.crmForm
  crmFormRef.value.validate(valid => {
    console.log("saveClick", valid)
    if (valid) {
      const params = createCustomFieldHook.getSubmiteParams([].concat.apply([], optionData.fieldList), optionData.fieldForm)
      console.log("saveClick", params)
      submitParams(params)
    } else {
      // 提示第一个error
      createCustomFieldHook.getFormErrorMessage(crmFormRef.value)
      // return false
    }
  })
}

/**
 * 提交上传
 */
function submitParams(params) {
  if (properties.action.type == 'update') {
    params.entity.customerId = properties.action.id
    params.entity.batchId = properties.action.batchId
  }
  // 相关添加时候的多余提交信息
  if (properties.action.relativeData && Object.keys(properties.action.relativeData).length) {
    params = {...params, ...properties.action.relativeData}
  }
  console.log("params", params)
  crmCustomerSaveAPI(params).then(res => {
    console.log("params", params)
    ElMessage.success({message: properties.action.type == 'update' ? '编辑成功' : '添加成功'})
    // .$message.success(.action.type == 'update' ? '编辑成功' : '添加成功')

    close()

    // 保存成功
    emits('save-success', {type: 'customer', data: res.data || {}})
  }).catch((e) => {
    console.log("params", params)
    console.log("e", e)
  })
}

onMounted(() => {
  getField(crmTypeModel.customer)
})

/**
 * 关闭
 */
function close() {
  emits('close')
}

// 从store中拿到crm权限
const crm = computed(() => {
  const erpUserStore = useErpUserStore();
  return erpUserStore.crm
})
const contactsSaveAuth = computed(() => {
  return crm.value.contacts && crm.value.contacts.save
})

function formChange(field, index, value, valueList) {
  if ([
        'select',
        'checkbox'
      ].includes(field.formType) &&
      field.remark === 'options_type' &&
      field.optionsData) {
    const {
      fieldForm,
      fieldRules
    } = createCustomFieldHook.getFormContentByOptionsChange(
        toRef(properties, "action"),
        toRef(optionData.fieldRules),
        optionData.fieldList,
        optionData.fieldForm)
    optionData.fieldForm = fieldForm
    optionData.fieldRules = fieldRules
  } else {
    optionData.fieldForm[field.field] = value
    console.log(optionData.fieldForm)
  }
}

/**
 * 获取数据
 * 在create页面中，后台接口查询的时候，如果有id，会返回key和value。如果没有id，就只返回key
 */
const createGenerateRuleHook = useCreateGenerateRuleHook();
const createCustomFieldHook = useCreateCustomFieldHook();

function getField(crmType) {
  const params = {
    label: crmType
  }

  if (properties.action.type == 'update') {
    params.id = properties.action.id
  }

  filedGetFieldAPI(params).then(res => {
    const list = res.data.data || []
    console.log("list", list)
    // assistIds 表单辅助id
    const assistIds = createCustomFieldHook.getFormAssistIds(list)

    const baseFields = []
    const fieldList = []
    const fieldRules = {}
    const fieldForm = {}
    list.forEach(children => {
      const fields = []
      children.forEach(item => {
        const temp = createCustomFieldHook.getFormItemDefaultProperty(item)
        console.log("temp", temp)
        temp.show = !assistIds.includes(item.formAssistId)

        const canEdit = createCustomFieldHook.getItemIsCanEdit(item, properties.action.type)
        // 是否能编辑权限
        if (temp.show && canEdit) {
          fieldRules[temp.field] = createGenerateRuleHook.getRules(item)
        }

        // 是否可编辑
        temp.disabled = !canEdit

        // 特殊字段允许多选
        createCustomFieldHook.getItemRadio(item, temp)

        // 获取默认值
        if (temp.show) {
          fieldForm[temp.field] =
              createCustomFieldHook.getItemValue(item, properties.action.data, properties.action.type)
        }
        fields.push(temp)
        baseFields.push(item)
      })
      fieldList.push(fields)
    })

    optionData.baseFields = baseFields
    optionData.fieldList = fieldList
    optionData.fieldForm = fieldForm
    optionData.fieldRules = fieldRules
    console.log("optionData", optionData)
  }).catch((error) => {
    console.log("数据获取错误", error)
  })
}
</script>


<template>
  <XrCreateSingle :title="title" @close="close" @save="saveClick">
    <CreateSections title="基本信息">
      <!--      optionData.fieldForm: {{optionData.fieldForm}}-->
      <!--      optionData.fieldList:{{optionData.fieldList}}-->
      <el-form ref="crmFormRef"
               :model="optionData.fieldForm"
               :rules="optionData.fieldRules"
               :validate-on-rule-change="false"
               class="wk-form"
               label-position="top">
        <WkFormItems v-for="(children, index) in optionData.fieldList" :key="index"
                     :field-from="optionData.fieldForm" :field-list="children"
                     @change="formChange">
          <template v-slot:default="{ data }">
            <div>这里了显示地图组件</div>
            <!-- <xh-customer-address v-if="data && data.formType == 'map_address'" :value="fieldForm[data.field]"-->
            <!-- @value-change="otherChange($event, data)"/>-->
          </template>
        </WkFormItems>
      </el-form>
    </CreateSections>

    <!--底部的插槽-->
    <template v-slot:footer>
      <!--如果有联系人保存权限，可以在创建完客户后，直接发起联系人创建流程-->
      <el-button v-if="action.type == 'save' && contactsSaveAuth" class="handle-button" type="primary"
                 v-on:click="saveClick">保存并新建联系人
      </el-button>
    </template>
  </XrCreateSingle>
</template>

<style scoped lang="scss">

</style>